from django.db import models

class Taxon(models.Model):
    name = models.CharField(max_length=128)
    def __unicode__(self):
        return self.name

class Word(models.Model):
    word = models.CharField(max_length=64)
    def __unicode__(self):
        return self.word

class WordMeaning(models.Model):
    word = models.ForeignKey(Word, related_name='meanings')
    taxon = models.ForeignKey(Taxon, related_name='words')
    text = models.TextField()
    def __unicode__(self):
        return self.word.word + ": " + self.text

class UsageType(models.Model):
    name = models.CharField(max_length=256)
    text = models.TextField()
    def __unicode__(self):
        return self.name

class Usage(models.Model):
    wordmeaning = models.ForeignKey(WordMeaning, related_name='usages')
    work = models.ForeignKey('Work', related_name='words_usages')
    pos_from = models.IntegerField()
    pos_to = models.IntegerField()
    usage_type = models.ForeignKey(UsageType)
    comment = models.TextField()
    def __unicode__(self):
        return self.wordmeaning.word.word + ": " + self.work.code + ": " + str(self.pos_from) + "-" + str(self.pos_to)
    def work_text(self):
        return "\n".join(self.work.text.splitlines()[self.pos_from:self.pos_to+1])
    class Meta:
        ordering = ('work', 'wordmeaning' )

class Person(models.Model):
    name = models.CharField(max_length=64)
    text = models.TextField(blank=True)
    usages = models.ManyToManyField(Usage, related_name="persons", blank=True)
    mentions = models.ManyToManyField('Work', related_name="persons", blank=True)
    def __unicode__(self):
        return self.name

class Work(models.Model):
    code = models.CharField(max_length=32)
    name = models.CharField(max_length=128)
    text = models.TextField()
    year = models.IntegerField()
    author = models.ForeignKey(Person, related_name='works', blank=True)
    def __unicode__(self):
        return self.code + ": " + self.name
    class Meta:
        ordering = ('code', )

